﻿//模拟实现atoi函数
//转化时跳过前面的空格字符，直到遇上数字或正负符号才开始做转换，而再遇到非数字或字符串结束时('/0')才结束转换，并将结果返回。
#include <stdio.h>
int my_atoi(const char* str)
{
	int sum = 0;
	int flag = 0;
	while (*str == ' ')
	{
		str++;
	}
	if ((*str != '+') && (*str != '-') && (*str < '0' || *str > '9'))
	{
		return -1;
	}
	if (*str == '-')
	{
		flag = 1;
		str++;
	}
	else if (*str == '+')
	{
		str++;
	}
	while (*str >= '0' && *str <= '9'&&*str!='\0')
	{
		sum = sum * 10 + (*str - '0');
		str++;
	}
	if (flag == 0) return sum;
	else if (flag == 1)return -sum;
}
int main()
{
	char str1[] = "98489";
	char str2[]="runoob.com";
	char str3[] = "-12345.12";
	char str4[]= "+1234w34";
	printf("%d\n", my_atoi(str1));
	printf("%d\n", my_atoi(str2));
	printf("%d\n", my_atoi(str3));
	printf("%d\n", my_atoi(str4));
}